import 'package:flutter/material.dart';
import 'package:flutter_app/common/utils/platform.dart';
import 'package:flutter_app/common/utils/screen.dart';
import 'package:flutter_app/common/values/colors.dart';
import 'package:flutter_app/common/widgets/widgets.dart';
import 'package:get/get.dart';
import 'package:share/share.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_app/common/values/values.dart';

import 'logic.dart';
import 'state.dart';

class DetailPage extends StatelessWidget {
  final DetailLogic logic = Get.put(DetailLogic());
  final DetailState state = Get.find<DetailLogic>().state;
  // 顶部导航
  PreferredSizeWidget _buildAppBar() {
    return transparentAppBar(
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: AppColors.primaryText,
          ),
          onPressed: () {
            Get.back();
          },
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.bookmark_border,
              color: AppColors.primaryText,
            ),
            onPressed: () {},
          ),
          IconButton(
            icon: Icon(
              Icons.share,
              color: AppColors.primaryText,
            ),
            onPressed: () {
              print(state.arguments?.url);
              Share.share('${state.arguments?.title} ${state.arguments?.url}');
              // Share.share('check out my website https://www.baidu.com/');

            },
          ),
        ]);
  }

// 页标题
  Widget _buildPageTitle() {
    return Container(
      margin: EdgeInsets.all(duSetWidth(10)),
      child: Row(
        children: <Widget>[
          Column(
            children: <Widget>[
              // 标题
              Text(
                state.arguments?.category ??"",
                style: TextStyle(
                  fontFamily: "Montserrat",
                  fontWeight: FontWeight.normal,
                  fontSize: duSetFontSize(30),
                  color: AppColors.thirdElement,
                ),
              ),
              // 作者
              Text(
                state.arguments?.author ?? "",
                style: TextStyle(
                  fontFamily: "Avenir",
                  fontWeight: FontWeight.normal,
                  fontSize: duSetFontSize(14),
                  color: AppColors.thirdElementText,
                ),
              ),
            ],
          ),
          Spacer(),
          // 标志
          CircleAvatar(
            //头像半径
            radius: duSetWidth(22),
            backgroundImage: AssetImage("assets/images/channel-fox.png"),
          ),
        ],
      ),
    );
  }

// 页头部
  Widget _buildPageHeader() {
    return Container(
      margin: EdgeInsets.all(duSetWidth(10)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          // 图
          imageCached(
            state.arguments?.thumbnail ?? "",
            width: duSetWidth(400),
            height: duSetHeight(290),
          ),
          // 标题
          Container(
            margin: EdgeInsets.only(top: duSetHeight(10)),
            child: Text(
              state.arguments?.title ?? "",
              style: TextStyle(
                fontFamily: 'Montserrat',
                fontWeight: FontWeight.w600,
                color: AppColors.primaryText,
                fontSize: duSetFontSize(24),
                height: 1,
              ),
            ),
          ),
          // 一行 3 列
          Container(
            margin: EdgeInsets.only(top: duSetHeight(10)),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                // 分类
                ConstrainedBox(
                  constraints: const BoxConstraints(
                    maxWidth: 120,
                  ),
                  child: Text(
                    state.arguments?.category??"",
                    style: TextStyle(
                      fontFamily: 'Avenir',
                      fontWeight: FontWeight.normal,
                      color: AppColors.secondaryElementText,
                      fontSize: duSetFontSize(14),
                      height: 1,
                    ),
                    overflow: TextOverflow.clip,
                    maxLines: 1,
                  ),
                ),
                // 添加时间
                Container(
                  width: duSetWidth(15),
                ),
                ConstrainedBox(
                  constraints: const BoxConstraints(
                    maxWidth: 120,
                  ),
                  child: Text(
                    '• ${state.arguments?.addtime}',
                    style: TextStyle(
                      fontFamily: 'Avenir',
                      fontWeight: FontWeight.normal,
                      color: AppColors.thirdElementText,
                      fontSize: duSetFontSize(14),
                      height: 1,
                    ),
                    overflow: TextOverflow.clip,
                    maxLines: 1,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );;
  }



// web内容
  Widget _buildWebView() {
    return Obx(() => Container(
      height: state.webViewHeight.value,
      child: WebView(
        initialUrl: '$SERVER_API_URL/news/content/${state.arguments?.id}', //widget.url,
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) async {
          state.webViewController.complete(webViewController);
        },
        javascriptChannels: <JavascriptChannel>[
          // 注册js回调
          _invokeJavascriptChannel(),
        ].toSet(),
        // navigation 拦截
        navigationDelegate: (NavigationRequest request) {
          if (request.url != '$SERVER_API_URL/news/content/${state.arguments?.id}') {
            toastInfo(msg: request.url);
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
        onPageStarted: (String url) {
          // Timer(Duration(seconds: 1), () {
          //   state.isPageFinished.value = true;
          //   // 删除广告
          //   _removeWebViewAd();
          //   // 获取页面高度
          //   _getWebViewHeight();
          // });
        },
        onPageFinished: (String url) {
          _getWebViewHeight();
          state.isPageFinished.value = true;
        },
        gestureNavigationEnabled: true,
      ),)
    );
  }

  // 注册js回调
  JavascriptChannel _invokeJavascriptChannel() {
    return JavascriptChannel(
        name: 'Invoke',
        onMessageReceived: (JavascriptMessage message) {
          print("message.message: ${message.message}");
          var webHeight = double.parse(message.message);
          state.webViewHeight.value = webHeight;
        });
  }

  // 删除广告
  _removeWebViewAd() async {
    await (await state.webViewController.future).evaluateJavascript('''
      try {
        function removeElement(elementName){
          let _element = document.getElementById(elementName);
          if(!_element) {
            _element = document.querySelector(elementName);
          }
          if(!_element) {
            return;
          }
          let _parentElement = _element.parentNode;
          if(_parentElement){
              _parentElement.removeChild(_element);
          }
        }

        removeElement('module-engadget-deeplink-top-ad');
        removeElement('module-engadget-deeplink-streams');
        removeElement('footer');
      } catch{}
      ''');
  }

  // 获取页面高度
  _getWebViewHeight() async {
    await (await state.webViewController.future).evaluateJavascript('''
        try {
          // Invoke.postMessage([document.body.clientHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight]);
          let scrollHeight = document.documentElement.scrollHeight;
          if (scrollHeight) {
            Invoke.postMessage(scrollHeight);
          }
        } catch {}
        ''');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            _buildPageTitle(),
            Divider(height: 1),
            _buildPageHeader(),
            PlatformUtil.isWeb?Text("web详情页面内容"):_buildWebView(),
          ],
        ),
      ),
    );;
  }
}
